package com.java.androidmarket.service.impl;

import com.java.androidmarket.dao.OrderDao;
import com.java.androidmarket.dto.order.GetOrderDTO;
import com.java.androidmarket.dto.order.OrderDTO;
import com.java.androidmarket.entity.KillStock;
import com.java.androidmarket.entity.Order;
import com.java.androidmarket.entity.OrderGoods;
import com.java.androidmarket.exception.ApiException;
import com.java.androidmarket.service.KillStockService;
import com.java.androidmarket.service.OrderGoodsService;
import com.java.androidmarket.service.OrderService;
import com.java.androidmarket.utils.JWTUtils;
import com.java.androidmarket.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * description:
 * author:张腾
 * date:2021-05-15
 */

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private KillStockService killStockService;
    @Autowired
    private OrderGoodsService orderGoodsService;


    @Override
    public int addOrder(Order order) {
        String orderSn = String.valueOf(System.currentTimeMillis() + order.getUserId());
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String createTime = now.format(formatter);

        order.setOrderSn(orderSn).setCreateTime(createTime).setOrderStatus(0);  //待支付状态
        return orderDao.addOrder(order);
    }

    @Override
    public List<GetOrderDTO> getAllOrder(int userId) {
        return orderDao.getAllOrder(userId);
    }

    @Override
    public GetOrderDTO getOneOrder(String orderSn) {
        return orderDao.getOneOrder(orderSn);
    }

    @Override
    public void changeStatus(Order order){
        orderDao.changeStatus(order);
    }

    @Override
    public List<GetOrderDTO> getOrderByStatus(int userId,int orderStatus) {

        Order order = new Order();
        order.setUserId(userId).setOrderStatus(orderStatus);
        List<GetOrderDTO> orderList = orderDao.getOrderByStatus(order);
        return orderList;
    }

    @Override
    public List<Map<String,Integer>> getOrderNum(int userId) {
        return orderDao.getOrderNum(userId);
    }

    @Override
    public void deleteOrder(String orderSn) {
        orderDao.deleteOrder(orderSn);
    }


    public void deleteRedis(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        int userId = Integer.valueOf(JWTUtils.DecodedGetID(request.getHeader("Token")));

        if (redisUtils.exists("AllOrder:"+userId)) {
            redisUtils.del("AllOrder:"+userId);
        }
        if (redisUtils.exists("StatusOrder:"+userId)) {
            redisUtils.del("StatusOrder:"+userId);
        }
    }
    public void deleteRedis(String orderSn){

        int userId = orderDao.getUserID(orderSn);

        if (redisUtils.exists("OneOrder:"+orderSn)){
            redisUtils.del("OneOrder:"+orderSn);
        }
        if (redisUtils.exists("AllOrder:"+userId)) {
            redisUtils.del("AllOrder:"+userId);
        }
        if (redisUtils.exists("StatusOrder:"+userId)) {
            redisUtils.del("StatusOrder:"+userId);
        }
    }

    @Override
    public int getOrderId(String orderSn) {
        return orderDao.getOrderID(orderSn);
    }

    @Override
    @Transactional
    public String addKillOrder(OrderDTO orderDTO) {

        Order order = orderDTO.getOrder();
        OrderGoods orderGoods = orderDTO.getOrderGoods();

        deleteRedis();
        //校验库存
        if (!killStockService.checkStock(orderGoods.getGoodsId(), orderGoods.getGoodsNum())) {
            System.out.println("库存不足");
            throw new ApiException("-1","商品库存不足！");
        }

        //锁定库存
        KillStock stock = killStockService.getStock(orderGoods.getGoodsId());
        if (killStockService.setLock(orderGoods.getGoodsId(), orderGoods.getGoodsNum(), stock.getVersion()) == 0) {
            System.out.println("抢购失败");
            throw new ApiException("-1","您的手速太慢啦，请稍后再试");
        }
        //新增订单记录
        addOrder(order);
        //将订单插入redis，10分钟后超时为订单关闭
        redisUtils.set("OOTKillOrder:" + order.getOrderSn(), "YES", 10L, TimeUnit.MINUTES);
        //新增订单商品
        orderGoods.setOrderId(order.getOrderId());
        orderGoodsService.insert(orderGoods);
        return order.getOrderSn();
    }




}
